"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : 多节点写入
Case Name   :  备节点开启事务，表1插入数据，重启主节点
Create At   : 2023/07/19
Owner       : opentestcase033
Description :
    1.修改enable_remote_execute参数值为on
    2.创建测试表
    3.备机开启事务，表中插入数据，查询
    4.重启主机
    5.新主（原备）查询表数据
    6.清理环境
Expect      :
    1.修改成功
    2.成功
    3.执行成功,两条数据
    4.成功
    5.表为空
    6.成功
History     :
    modified: 2025/03/05 modified by kyleze,参数值变化,优化用例
"""
import os
import time
import unittest

from yat.test import Node
from yat.test import macro
from testcase.utils.Logger import Logger
from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.ComThread import ComThread

PrimarySh = CommonSH('PrimaryDbUser')


@unittest.skipIf(1 == PrimarySh.get_node_num(),
                 'Single node, and subsequent codes are not executed.')
class MultiNodeWrite(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f"-----{os.path.basename(__file__)} start-----")
        self.standby_sh = CommonSH('Standby1DbUser')
        self.pri_node = Node('PrimaryDbUser')
        self.constant = Constant()
        self.common = Common('Standby1DbUser')
        self.table = 't_multi_node_write_0067'
        self.enable_remote_execute = 'enable_remote_execute'
        self.remote_excute_default = self.common.show_param(
            self.enable_remote_execute)

    def test_multi_node_write(self):
        step1 = "-----step1:修改enable_remote_execute参数值为on;expect:修改成功-----"
        self.log.info(step1)
        result = self.standby_sh.execute_gsguc(
            'set', self.constant.GSGUC_SUCCESS_MSG,
            f'{self.enable_remote_execute}=on')
        self.assertTrue(result, f'执行失败:{step1}')
        restart_res = self.standby_sh.restart_db_cluster()
        self.assertTrue(restart_res, f'执行失败:{step1}')
        show_remote_excute = self.common.show_param(self.enable_remote_execute)
        self.assertEquals(show_remote_excute, 'on', f'执行失败:{step1}')

        step2 = "-----step2:创建测试表;expect:成功-----"
        self.log.info(step2)
        sql_msg = self.standby_sh.execut_db_sql(
            f'''drop table if exists {self.table} cascade;
            create table {self.table}(col1 int, col2 int) 
            with(segment=on) partition by list(col1)(
            partition p1 values (2000),
            partition p2 values (3000),
            partition p3 values (4000),
            partition p4 values (5000));''')
        self.log.info(sql_msg)
        self.assertIn(self.constant.CREATE_TABLE_SUCCESS,
                      sql_msg, f'执行失败:{step2}')
        time.sleep(5)

        step3 = "-----step3:备机开启事务，表中插入数据，查询;expect:执行成功,两条数据-----"
        self.log.info(step3)
        sql = f'''begin;
        insert into {self.table} values(2000, 2),(3000, 3);
        update {self.table} set col2=3 where col1=2000;
        select * from {self.table} order by 1;
        select pg_sleep(90);'''
        self.log.info(sql)
        session1 = ComThread(self.standby_sh.execut_db_sql, args=(sql,))
        session1.setDaemon(True)
        session1.start()
        time.sleep(2)

        step4 = "-----step4:重启主机;expect:成功-----"
        self.log.info(step4)
        cmd = f"source {macro.DB_ENV_PATH};" \
              f"cm_ctl stop -n 1 && cm_ctl start -n 1"
        self.log.info(cmd)
        session2 = ComThread(self.common.get_sh_result,
                             args=(self.pri_node, cmd))
        session2.setDaemon(True)
        session2.start()
        session1.join(90)
        session2.join(95)
        res1 = session1.get_result()
        self.log.info(f'session1_results:\n {res1}')
        res2 = session2.get_result()
        self.log.info(f'session2_results:\n {res2}')
        self.assertIn('BEGIN', res1, f"执行失败: {step3}")
        self.assertIn(self.constant.INSERT_SUCCESS_MSG, res1, f"执行失败: {step3}")
        self.assertIn('2000 |    3', res1, f"执行失败: {step3}")
        self.assertIn('3000 |    3', res1, f"执行失败: {step3}")
        self.assertIn(self.constant.cm_start_node_success_msg, res2,
                      f"执行失败: {step4}")

        step5 = "-----step5:新主（原备）查询表数据;expect:成功-----"
        self.log.info(step5)
        time.sleep(5)
        sql_msg = self.standby_sh.execut_db_sql(f"select * from {self.table};")
        self.log.info(sql_msg)
        self.assertIn('(0 rows)', sql_msg, f'执行失败:{step5}')

    def tearDown(self):
        step6 = "-----step6:恢复参数;expect:恢复参数成功-----"
        self.log.info(step6)
        cmd = f"source {macro.DB_ENV_PATH};cm_ctl switchover -a"
        self.log.info(cmd)
        switch_res = self.common.get_sh_result(self.pri_node, cmd)
        self.log.info(switch_res)
        drop_res = self.standby_sh.execut_db_sql(
            f'drop table if exists {self.table} cascade;')
        result1 = self.standby_sh.execute_gsguc(
            'set', self.constant.GSGUC_SUCCESS_MSG,
            f'{self.enable_remote_execute}={self.remote_excute_default}')
        restart_res = self.standby_sh.restart_db_cluster()
        show_remote_excute = self.common.show_param(self.enable_remote_execute)
        self.assertIn(self.constant.cm_switchover_success_msg, switch_res,
                      f"执行失败: {step6}")
        self.assertIn(self.constant.DROP_TABLE_SUCCESS, drop_res,
                      f'执行失败:{step6}')
        self.assertTrue(result1, f'执行失败:{step6}')
        self.assertTrue(restart_res, f'执行失败:{step6}')
        self.assertEquals(show_remote_excute, self.remote_excute_default,
                          f'执行失败:{step6}')
        self.log.info(f"-----{os.path.basename(__file__)} end-----")
